/**
 * 
 */
package com.simple.user;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.simplecms.util.DateUtil;

/**
 * 系统用户控制器
 * @author zhanxj
 *
 */
public class UserController  extends Controller {
	
	public void index() {
		render("/login/login.jsp");
	}
	/**
	 * 登入
	 */
	public void login(){
		String username=getPara("username");
		String password=getPara("password");
		List<User> resultList=User.dao.queryUserByNameAndPassword(username, password);
		if(resultList.size()>0&&(resultList.get(0).getInt(User.ISONLINE)==0)){
			//登陆成功
			User.dao.findById(resultList.get(0).getInt(User.ID)).set(User.ISONLINE, 1).set(User.LASTLOGINTIME, new Date()).update();
			setSessionAttr("userInfo", resultList.get(0).get(User.USERNAME));
			setSessionAttr("lastTime", DateUtil.getInstance().getDateStrByTimestamp((Timestamp)(resultList.get(0).get(User.LASTLOGINTIME)),
							DateUtil.DATESTR_STYLE3));
			render("/login/index.jsp");
		}else if(resultList.size()>0&&(resultList.get(0).getInt(User.ISONLINE)==1)){
			setAttr("loginInfo","当前用户在线");
			render("/login/login.jsp");
		}else{
			setAttr("loginInfo","账号或密码错误");
			render("/login/login.jsp");
		}
		
	}
	/**
	 * 登出
	 */
	@Before(UserInterceptor.class)
	public void logout(){
		String userName=getPara("userName");
		List<User> resultList=User.dao.queryUserByName(userName);
		if(resultList.size()>0){
			resultList.get(0).set(User.ISONLINE, 0).update();
			removeSessionAttr("loginInfo");
			redirect("/login/login.jsp");
		}
	}
	/**
	 * 注册
	 */
	public void regist(){
		String username=getPara("username");
		List<User> resultList=User.dao.queryUserByName(username);
		if(resultList.size()>0){
			getModel(User.class).save();
		}else{
			setAttr("registInfo","该用户已被注册" );
			render("/login/regist.jsp");
		}
	}
}
